package com.jy.servlet;

import com.jy.bean.ShoppingTrolley;
import com.jy.bean.User;
import com.jy.service.ShoppingTrolleyService;
import com.jy.service.UserService;
import com.jy.service.impl.ShoppingTrolleySericelmpl;
import com.jy.service.impl.UserServicelmpl;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.List;

public class ShoppingTrolleyServlet extends HttpServlet {
    private static final Logger log = LoggerFactory.getLogger(goodsDetailServlet.class);
    private ShoppingTrolleyService shoppingTrolleyService;
    private UserService userService;
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String user_name = request.getParameter("user_name");
        String id = request.getParameter("consignee_id");
        String commodity_name = request.getParameter("commodity_name");
        String Price = request.getParameter("commodity_Price");
        userService = new UserServicelmpl();
        List<User> users = userService.selectByname(user_name);
        int user_id = 0;
        for (User user:users){
            user_id = user.getId();
        }
        int consignee_id = Integer.parseInt(id);
        int commodity_Price = Integer.parseInt(Price);
        shoppingTrolleyService = new ShoppingTrolleySericelmpl();

        //查询购物车有没有现在添加的商品，如果没有就添加这个商品，如果有就在该商品在购物车的数量添加1;
        int quantity = shoppingTrolleyService.selectQuantity(user_id,consignee_id);
        if (quantity<=0){
            if (shoppingTrolleyService.register(new ShoppingTrolley(null,user_id,consignee_id,commodity_name,commodity_Price,1))){
                //查询该账号的购物车数量，并给到session里面去
                HttpSession session = request.getSession();
                int Shopping_count = shoppingTrolleyService.selectByName(user_name);
                session.setAttribute("Shopping_count",Shopping_count);
                request.getRequestDispatcher("/cartSuccess.jsp").forward(request,response);
            }else {
                request.getRequestDispatcher("/www.mi.com.jsp").forward(request,response);
            }
        } else {
          if (shoppingTrolleyService.updateQuantity(new ShoppingTrolley( null, user_id, consignee_id, commodity_name, commodity_Price, quantity+1))){
              request.getRequestDispatcher("/cartSuccess.jsp").forward(request,response);
          }else {
              request.getRequestDispatcher("/www.mi.com.jsp").forward(request,response);
          }
        }
    }
}
